<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-nav :all-show="true">
        <template>
          <span slot="before">共{{ page.total }}条数据</span>
        </template>
        <template v-slot:after>
          <el-button type="warning" @click="$router.push('./import')">导入excel</el-button>
          <el-button type="danger" @click="exportData">导出excel</el-button>
          <el-button type="primary" @click="showDiaglog= true">新增员工</el-button>
        </template>
      </page-nav>

      <el-card>
        <el-row type="flex" justify="end">
          <el-tooltip content="打印个人基本信息">
            <router-link to="">
              <i class="el-icon-printer" />
            </router-link>
          </el-tooltip>
        </el-row>
        <el-table :data="tableData" border>
          <el-table-column type="index" label="序号" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                slot="reference"
                v-imagerror="a"
                :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrcode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />

          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" :formatter="formatterData" label="聘用形式" sortable />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="{ row}">
              {{ row.correctionTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template slot-scope="{row}">
              <el-switch
                :value="row.enableState===1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row}">
              <el-button type="text" size="small" @click="$router.push(`/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="cancelUser(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :page-size="page.size" :current-page="page.page" :total="page.total" @current-change="currentChange" />
        </el-row>
      </el-card>
      <!-- 新增 -->
      <add-employee :show-diaglog.sync="showDiaglog" @addEmploy="addEmploy" />
      <el-dialog title="二维码" :visible.sync="showDialogs">
        <el-row type="flex" justify="center">
          <canvas ref="canvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployees } from '@/api/employee'
import EmployeeMent from '@/api/constant/employees'
import { delEmployees } from '@/api/employee'
import AddEmployee from './component/addEmployee.vue'
import { formatDate } from '@/filters'
import QRcode from 'qrcode'
export default {
  components: {
    AddEmployee
  },
  data() {
    return {
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      tableData: [],
      showDiaglog: false,
      a: require('@/assets/common/img.jpeg'),
      showDialogs: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    showQrcode(url) {
      if (url) {
        this.showDialogs = true
        this.$nextTick(() => {
          QRcode.toCanvas(this.$refs.canvas, url)
        })
      } else {
        this.$message.warning('该图片没有地址')
      }
    },
    async getEmployeeList() {
      const result = await getEmployees(this.page)
      console.log(result)
      this.tableData = result.rows
      this.page.total = result.total
    },
    currentChange(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatterData(row, column, cellValue, index) {
      const isData = EmployeeMent.hireType.find(item => Number(item.id) === Number(cellValue))
      return isData ? isData.value : '未知'
    },
    // 删除操作
    async cancelUser(id) {
      try {
        await confirm('确认删除吗?')
        await delEmployees(id)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    addEmploy(val) {
      this.showDiaglog = val
      this.getEmployeeList()
    },
    exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',

        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployees({ page: 1, size: this.page.total })
        const data = this.formatData(headers, rows)
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工工资',
          multiHeader,
          merges

        })
        // 将中文转化为英文
      })
    },
    formatData(headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeMent.hireType.find(obj => Number(obj.id) === Number(item[headers[key]]))
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }

  }
}
</script>

<style>

</style>
